<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
  
    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];
    /**
     * 查看
     */
    public function index()
    {
        

        $result['huizong'] = [];


        $map['paystate'] = 1;
        $map['shippingstate'] = 0;


        $result['huizong']['all']= Db::table('fa_pifa_order')->where($map)->field('count(*) as num,sum(price) as price')->select()[0];
        $map['createday'] = ['BETWEEN',[date('Y-01-01'),date('Y-12-31')]];
        $result['huizong']['year'] = Db::table('fa_pifa_order')->where($map)->field('count(*) as num,sum(price) as price')->select()[0];
        $map['createday'] = ['BETWEEN',[date('Y-m-01'),date('Y-m-31')]];
        $result['huizong']['month'] = Db::table('fa_pifa_order')->where($map)->field('count(*) as num,sum(price) as price')->select()[0];


        $map['createday'] = ['BETWEEN',[date('Y-m-d'),date('Y-m-d')]];
        $result['today']['order'] = Db::table('fa_pifa_order')->where($map)->field('count(*) as num,sum(price) as price')->select()[0];


        $map2['createday'] = ['BETWEEN',[date('Y-m-d'),date('Y-m-d')]];
        $map2['paystate'] = 0;

        $result['today']['order']['nopay'] = Db::table('fa_pifa_order')->where($map2)->count();




        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $map['createday'] = ['BETWEEN', [$yesterday, $yesterday]];
        $result['yesterday']['order'] = Db::table('fa_pifa_order')->where($map)->field('count(*) as num,sum(price) as price')->select()[0];


        $map2['createday'] =  ['BETWEEN', [$yesterday, $yesterday]];
        $map2['paystate'] = 0;
        $result['yesterday']['order']['nopay'] = Db::table('fa_pifa_order')->where($map2)->count();




        $Order = new \app\admin\model\pifa\Order;

        $map4['paystate'] = 1;
        $map4['shippingstate'] = 0;
        $order_top = Db::table('fa_pifa_order')
        ->alias('o')
        ->field('count(*) as num, o.user_id, sum(o.price) as price, s.nickname as shangjia_name')
        ->join('fa_user s', 'o.user_id = s.id', 'LEFT')
        ->where($map4)->group('user_id')->order('price desc,num desc')->limit(10)->select();



        $map4['fa_pifa_order.inv_id'] = ['<>',0];
        $order_top2 = Db::table('fa_pifa_order')
        ->alias('o')
        ->field('count(*) as num, o.inv_id, sum(o.price) as price, s.nickname as shangjia_name')
        ->join('fa_user s', 'o.inv_id = s.id', 'LEFT')
        ->where($map4)->group('inv_id')->order('price desc,num desc')->limit(10)->select();

        $map5['fa_pifa_orderitem.status'] = '1';    
        $order_top3 = Db::table('fa_pifa_orderitem')
        ->field('count(*) as num,sum(price) as price, goods_name,goods_item_id')
        ->where($map5)->group('goods_item_id')->order('price desc,num desc')->limit(10)->select();


        $order_orderstate = Db::table('fa_pifa_order')->group('orderstate')->column('count(*) as num','orderstate');


        $order_tuikuan = Db::table('fa_pifa_order')->where('sh_status','=',1)->count();
        $md_sq = Db::table('fa_pifa_md')->where('status','=','0')->count();


     
        $map_user['createtime'] = ['BETWEEN',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]];
        $result['today']['reg_user'] = Db::table('fa_user')->where($map_user)->count();
        $map_user['createtime'] = ['BETWEEN', [
            strtotime(date('Y-m-d 00:00:00', strtotime('-1 day'))),
            strtotime(date('Y-m-d 23:59:59', strtotime('-1 day')))
        ]];
        $result['yesterday']['reg_user'] = Db::table('fa_user')->where($map_user)->count();


        
     
        $this->view->assign("huizong", $result['huizong']);
        $this->view->assign("today", $result['today']);
        $this->view->assign("yesterday", $result['yesterday']);
        $this->view->assign("order_top", $order_top);
        $this->view->assign("order_top2", $order_top2);
        $this->view->assign("order_top3", $order_top3);
        $this->view->assign("order_orderstate", $order_orderstate);
        $this->view->assign("order_tuikuan", $order_tuikuan);
        $this->view->assign("md_sq", $md_sq);


        return $this->view->fetch();
    }


    public function getOrderDataPrice()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->field('createday, sum(price) as total')
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
            ->group('createday')
            ->select();

        $dateMap = [];
        for ($d = $start; $d <= $end; $d += 86400) {
            $dateStr = date('Y-m-d', $d);
            $dateMap[$dateStr] = 0;
        }

        // 把数据库结果填进去
        foreach ($rows as $row) {
            $day = $row['createday'];
            $dateMap[$day] = (int)$row['total'];
        }

        // 拆出两个数组用于前端
        $result['xAxis'] = array_keys($dateMap);   // 日期
        $result['seriesData']= array_values($dateMap); // 数量

         $this->success('提交成功',200,$result);


    }

    public function getOrderDataNum()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->field('createday, COUNT(*) as total')
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
            ->group('createday')
            ->select();

        $dateMap = [];
        for ($d = $start; $d <= $end; $d += 86400) {
            $dateStr = date('Y-m-d', $d);
            $dateMap[$dateStr] = 0;
        }

        // 把数据库结果填进去
        foreach ($rows as $row) {
            $day = $row['createday'];
            $dateMap[$day] = (int)$row['total'];
        }

        // 拆出两个数组用于前端
        $result['xAxis'] = array_keys($dateMap);   // 日期
        $result['seriesData']= array_values($dateMap); // 数量

         $this->success('提交成功',200,$result);

    }

    public function getOrderData()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->field("createday, COUNT(*) as total, SUM(price) as total_price, SUM(IFNULL(price,0) - IFNULL(chengben,0)) as lirun")
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
            ->group('createday')
            ->select();

        $dateMap = [];
        for ($d = $start; $d <= $end; $d += 86400) {
            $dateStr = date('Y-m-d', $d);
            $dateMap[$dateStr] = 0;
            $priceMap[$dateStr] = 0;
            $lirunMap[$dateStr] = 0;
        }

        // 把数据库结果填进去
        foreach ($rows as $row) {
            $day = $row['createday'];
            $dateMap[$day] = (int)$row['total'];
            $priceMap[$day] = (float)$row['total_price'];
            // $lirunMap[$day] = (float)$row['lirun'];
        }

        // 拆出两个数组用于前端
        $result['xAxis'] = array_keys($dateMap);   // 日期
        $result['series'] = [
            [
                'name' => '订单数量',
                'type' => 'line',
                'data' => array_values($dateMap)
            ],
            [
                'name' => '订单总额',
                'type' => 'line',
                'data' => array_values($priceMap)
            ],
            // [
            //     'name' => '利润',
            //     'type' => 'line',
            //     'data' => array_values($lirunMap)
            // ]
        ];

        $this->success('提交成功',200,$result);

    }


    public function getOrderOrderItemTop()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        $startTime = strtotime($s_day . ' 00:00:00');
        $endTime = strtotime($e_day . ' 23:59:59');

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_orderitem')
            ->field("FROM_UNIXTIME(createtime, '%Y-%m-%d') as createday, COUNT(*) as total, SUM(price*goods_num) as total_price, SUM(IFNULL(price,0) - IFNULL(goods_price4,0)) as lirun")
            ->whereBetween('createtime', [$startTime, $endTime])
            ->group('createday')
            ->where('status', '=', 1)
            ->select();

        $dateMap = [];
        for ($d = $start; $d <= $end; $d += 86400) {
            $dateStr = date('Y-m-d', $d);
            $dateMap[$dateStr] = 0;
            $priceMap[$dateStr] = 0;
            $lirunMap[$dateStr] = 0;
        }

        // 把数据库结果填进去
        foreach ($rows as $row) {
            $day = $row['createday'];
            $dateMap[$day] = (int)$row['total'];
            $priceMap[$day] = (float)$row['total_price'];
            $lirunMap[$day] = (float)$row['lirun'];
            
        }

        // 拆出两个数组用于前端
        $result['xAxis'] = array_keys($dateMap);   // 日期
        $result['series'] = [
            [
                'name' => '数量',
                'type' => 'line',
                'data' => array_values($dateMap)
            ],
            [
                'name' => '总销售额',
                'type' => 'line',
                'data' => array_values($priceMap)
            ],
            //  [
            //     'name' => '利润',
            //     'type' => 'line',
            //     'data' => array_values($lirunMap)
            // ]
        ];

        $this->success('提交成功',200,$result);

    }


    public function getOrderUserTop()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        $startTime = strtotime($s_day . ' 00:00:00');
        $endTime = strtotime($e_day . ' 23:59:59');

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->alias('o')
            ->field("COUNT(*) as total, o.user_id, sum(o.price) as total_price, s.nickname as shangjia_name")
            ->join('fa_user s', 'o.user_id = s.id', 'LEFT')    
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
            ->group('user_id')
            ->order('total_price desc')
            ->limit(5)
            ->select();

       

        $user_ids = [];
        $dateMap = [];
        $priceMap = [];
        foreach ($rows as $key => $value) {
            $user_ids[$key] = $value['shangjia_name'];
            $dateMap[$key] = (int)$value['total'];
            $priceMap[$key] = (float)$value['total_price'];  
        }


       
        // 拆出两个数组用于前端
        $result['xAxis'] = $user_ids;   // 日期
        $result['series'] = [
            [
                'name' => '数量',
                'type' => 'line',
                'data' => array_values($dateMap)
            ],
            [
                'name' => '总销售额',
                'type' => 'line',
                'data' => array_values($priceMap)
            ], 
        ];

        $this->success('提交成功',200,$result);

    }



    public function getOrderFenleiTop()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        $startTime = strtotime($s_day . ' 00:00:00');
        $endTime = strtotime($e_day . ' 23:59:59');

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_orderitem')
        ->alias('oi')
        ->join('fa_litestore_goods g', 'oi.goods_id = g.goods_id', 'LEFT')
        ->join('fa_litestore_category c', "c.id = SUBSTRING_INDEX(g.category_id, ',', 1)", 'LEFT')
        ->field([
            'SUBSTRING_INDEX(g.category_id, ",", 1)' => 'top_category_id',
            'c.name' => 'category_name',
            'sum(goods_num*price)' => 'total_sales'
        ])
        ->whereBetween('oi.createtime', [$startTime, $endTime]) 
        ->where('oi.status', '=', 1)
        ->group('top_category_id')
        ->order('total_sales DESC')
        ->select();
       

        // var_dump($rows);


       
        // 拆出两个数组用于前端
        $xAxis = [];
        $seriesData = [];

        foreach ($rows as $row) {
            $xAxis[] = $row['category_name'] ?: '未知分类';
            $seriesData[] = round($row['total_sales'], 2); // 或用 $row['total_num']
        }

        $result['xAxis'] = $xAxis;
        $result['series'] = [
            [
                'name' => '销售额',
                'type' => 'line',
                'data' => $seriesData
            ],
           
        ];

        $this->success('获取成功', 200, $result);

    }

     public function getorderlirun()
    {


        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->field("COUNT(*) as total, SUM(price) as price,SUM(chengben) as chengben,SUM(yunfei) as yunfei, SUM(IFNULL(price,0) - IFNULL(chengben,0)) as lirun")
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
           
            ->find();

        
    
        $result['series'] = [
            [
                'name' => '利润金额',
                'value' => isset($rows['lirun']) ? $rows['lirun'] :0
            ],
            [
                'name' => '配送金额',
                'value' =>isset($rows['yunfei']) ? $rows['yunfei'] :0
            ],
            [
                'name' => '成本金额',
                'value' =>isset($rows['chengben'])  ? $rows['chengben'] :0
            ],
            [
                'name' => '销售额',
                
                'value' => isset($rows['price']) ? $rows['price'] :0
            ],
            
           
        ];

        $this->success('提交成功',200,$result);
    }


     public function getOrderDatalirun()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->field("createday, COUNT(*) as total, SUM(price) as total_price, SUM(IFNULL(price,0) - IFNULL(chengben,0)) as lirun")
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
            ->group('createday')
            ->select();

        $dateMap = [];
        for ($d = $start; $d <= $end; $d += 86400) {
            $dateStr = date('Y-m-d', $d);
            $dateMap[$dateStr] = 0;
            $priceMap[$dateStr] = 0;
            $lirunMap[$dateStr] = 0;
        }

        // 把数据库结果填进去
        foreach ($rows as $row) {
            $day = $row['createday'];
            $dateMap[$day] = (int)$row['total'];
            $priceMap[$day] = (float)$row['total_price'];
            $lirunMap[$day] = (float)$row['lirun'];
        }

        // 拆出两个数组用于前端
        $result['xAxis'] = array_keys($dateMap);   // 日期
        $result['series'] = [
            [
                'name' => '订单数量',
                'type' => 'line',
                'data' => array_values($dateMap)
            ],
            
            [
                'name' => '利润',
                'type' => 'line',
                'data' => array_values($lirunMap)
            ]
        ];

        $this->success('提交成功',200,$result);

    }

    public function getOrderOrderItemToplirun()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        $startTime = strtotime($s_day . ' 00:00:00');
        $endTime = strtotime($e_day . ' 23:59:59');

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_orderitem')
            ->field("FROM_UNIXTIME(createtime, '%Y-%m-%d') as createday, SUM(goods_num) as total, SUM(IFNULL(price*goods_num,0) - IFNULL(goods_price4*goods_num,0)) as lirun")
            ->whereBetween('createtime', [$startTime, $endTime])
            ->group('createday')
            ->where('status', '=', 1)
            ->select();

        $dateMap = [];
        for ($d = $start; $d <= $end; $d += 86400) {
            $dateStr = date('Y-m-d', $d);
            $dateMap[$dateStr] = 0;
            $priceMap[$dateStr] = 0;
            $lirunMap[$dateStr] = 0;
        }

        // 把数据库结果填进去
        foreach ($rows as $row) {
            $day = $row['createday'];
            $dateMap[$day] = (int)$row['total'];
            $lirunMap[$day] = (float)$row['lirun'];
            
        }

        // 拆出两个数组用于前端
        $result['xAxis'] = array_keys($dateMap);   // 日期
        $result['series'] = [
            [
                'name' => '数量',
                'type' => 'line',
                'data' => array_values($dateMap)
            ],
            [
                'name' => '利润',
                'type' => 'line',
                'data' => array_values($lirunMap)
            ]
        ];

        $this->success('提交成功',200,$result);

    }


    public function getOrderUserToplirun()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        $startTime = strtotime($s_day . ' 00:00:00');
        $endTime = strtotime($e_day . ' 23:59:59');

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_order')
            ->alias('o')
            ->field("COUNT(*) as total, o.user_id, sum(o.price-o.chengben) as total_price, s.nickname as shangjia_name")
            ->join('fa_user s', 'o.user_id = s.id', 'LEFT')    
            ->where('createday', 'between', [$s_day, $e_day])
            ->where('paystate', '=', 1)
            ->where('shippingstate', '=', 0)
            ->group('user_id')
            ->order('total_price desc')
            ->limit(5)
            ->select();

       

        $user_ids = [];
        $dateMap = [];
        $priceMap = [];
        foreach ($rows as $key => $value) {
            $user_ids[$key] = $value['shangjia_name'];
            $dateMap[$key] = (int)$value['total'];
            $priceMap[$key] = (float)$value['total_price'];  
        }


       
        // 拆出两个数组用于前端
        $result['xAxis'] = $user_ids;   // 日期
        $result['series'] = [
            [
                'name' => '数量',
                'type' => 'line',
                'data' => array_values($dateMap)
            ],
            [
                'name' => '利润',
                'type' => 'line',
                'data' => array_values($priceMap)
            ], 
        ];

        $this->success('提交成功',200,$result);

    }



    public function getOrderFenleiToplirun()
    {
        $post = $this->request->request();

        $s_day = $post['start'];  //2025-07-21
        $e_day = $post['endStr']; //2025-07-28


        $start = strtotime($s_day);
        $end = strtotime($e_day);

        $startTime = strtotime($s_day . ' 00:00:00');
        $endTime = strtotime($e_day . ' 23:59:59');

        // 第一步：查询统计结果
        $rows = Db::table('fa_pifa_orderitem')
        ->alias('oi')
        ->join('fa_litestore_goods g', 'oi.goods_id = g.goods_id', 'LEFT')
        ->join('fa_litestore_category c', "c.id = SUBSTRING_INDEX(g.category_id, ',', 1)", 'LEFT')
        ->field([
            'SUBSTRING_INDEX(g.category_id, ",", 1)' => 'top_category_id',
            'c.name' => 'category_name',
            'SUM(IFNULL(oi.price*oi.goods_num,0) - IFNULL(oi.goods_price4*oi.goods_num,0))' => 'total_sales'
        ])
        ->whereBetween('oi.createtime', [$startTime, $endTime]) 
        ->where('oi.status', '=', 1)
        ->group('top_category_id')
        ->order('total_sales DESC')
        ->select();
       

        // var_dump($rows);


       
        // 拆出两个数组用于前端
        $xAxis = [];
        $seriesData = [];

        foreach ($rows as $row) {
            $xAxis[] = $row['category_name'] ?: '未知分类';
            $seriesData[] = round($row['total_sales'], 2); // 或用 $row['total_num']
        }

        $result['xAxis'] = $xAxis;
        $result['series'] = [
            [
                'name' => '利润',
                'type' => 'line',
                'data' => $seriesData
            ],
           
        ];

        $this->success('获取成功', 200, $result);

    }





}
